<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form onsubmit="return false">
        <textarea id="message" style="height: 300px; width: 300px;"></textarea>
        <input type="button" value="发送消息" onclick="send()">
        <textarea id="response" style="height: 300px; width: 300px;"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('response').value = ''">
    </form>
    <script>
        if (!window.WeakSet) {
            alert("当前浏览器不支持 WebSocket连接")
        }
        var socket = new WebSocket("ws://localhost:7777/hello");
        var context = document.getElementById("response");
        socket.onmessage = function(e) {
            context.value = context.value + '\n' + e.data;
        }
        socket.onopen = function(e) {
            context.value = context.value + '\n 连接建立...';
        }
        socket.onclose = function(e) {
            context.value = context.value + '\n 连接关闭...';
        }

        function send() {
            if (!window.socket) {
                return;
            }
            var context = document.getElementById("message");
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(context.value);
                // 发送后清空发送框内容
                context.value = ''
            } else {
                alert("连接未开启...")
            }
        }
    </script>
</body>
</html>